package com.northpool.operator.common.string;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.alibaba.fastjson.JSONObject;
import com.northpool.operator.annotation.InputParam;
import com.northpool.operator.annotation.InputParams;
import com.northpool.operator.annotation.OperatorInfo;
import com.northpool.operator.annotation.OutputParam;
import com.northpool.operator.annotation.OutputParams;
import com.northpool.operator.common.algorithm.OperatorTestBuild;
import com.northpool.operator.common.algorithm.TestParamBuilder;
import com.northpool.operator.param.ParamTool;
import com.northpool.operator.type.TypeEnum;
import com.northpool.operator.utils.StpOperatorHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

@OperatorInfo(
        ref = "ReCheckOperator",
        name = "正则校验",
        description = "提供正则表达式匹配与验证功能"
)
@OutputParams({
        @OutputParam(ref = "isMatched", name = "是否匹配", desc = "匹配结果布尔值"),
        @OutputParam(ref = "matches", name = "匹配结果集", desc = "匹配结果列表，Json数组"),
})
public class ReCheckOperator extends StpOperatorHelper {

    @InputParams({
            @InputParam(ref = "pattern", name = "正则表达式", desc = "正则表达式", required = true),
            @InputParam(ref = "input", name = "输入内容", desc = "内容字符串", required = true),
            @InputParam(ref = "globalMatch", name = "全局匹配", desc = "是否全局匹配", type = TypeEnum.BOOL, value = "false")
    })
    public ReCheckOperator() {
        super();
    }


    public static void main(String[] args) throws Exception {
        OperatorTestBuild.execute(ReCheckOperator.class,
                TestParamBuilder.aBuilder()
                        .param("pattern", "[1-9]+")
                        .param("input", "http://192.168.164.45")
                        .param("globalMatch", "true")
                        .build());
    }

    @Override
    public void execute(ParamTool params) {
        try {
            String regex = params.getStr("pattern");
            String input = params.getStr("input");
            boolean globalMatch = params.getBool("globalMatch");

            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(input);

            processMatchResult(matcher, globalMatch);
        } catch (PatternSyntaxException e) {
            handlePatternError(e);
        } catch (Exception e) {
            handleCommonError(e);
        }
    }

    private void processMatchResult(Matcher matcher, boolean globalMatch) {
        List<String> matches = new ArrayList<>();
        boolean isMatched = false;

        if (globalMatch) {
            while (matcher.find()) {
                matches.add(getMatchContent(matcher));
                isMatched = true;
            }
        } else {
            if (matcher.find()) {
                matches.add(getMatchContent(matcher));
                isMatched = true;
            }
        }

        this.result("isMatched", String.valueOf(isMatched));
        this.result("matches", isMatched ? JSONObject.toJSONString(matches) : "[]");
    }

    private String getMatchContent(Matcher matcher) {
        return matcher.groupCount() > 0 ?
                matcher.group(1) :  // 返回第一个捕获组
                matcher.group();    // 返回完整匹配
    }

    private void handlePatternError(PatternSyntaxException e) {
        this.result("isMatched", false);
        this.result("error", "正则表达式语法错误: " + e.getDescription());
        this.error("正则表达式错误: " + e.getPattern());
    }

    private void handleCommonError(Exception e) {
        this.result("isMatched", false);
        this.result("error", ExceptionUtil.getRootCauseMessage(e));
        this.error("执行异常: " + e.getMessage());
    }

}
